<template>
  <div>
    <!-- 面包屑区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <!-- 按钮区域 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="addRolesDialog = true">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 表格区域 -->
      <el-table :data="rolesList" stripe border>
        <el-table-column align="center" type="index" label="#"></el-table-column>
        <!-- 在这里添加一个展开行 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <!-- 通过渲染角色来获得一级权限在遍历插值 -->
            <el-row
              :class="['.vcenter','btmborder', i1 === 0 ? 'tborder' : '']"
              v-for="(item1, i1) in scope.row.children"
              :key="item1.id"
            >
              <el-col :span="5">
                <el-tag
                  size="medium"
                  type="primary"
                  closable
                  @close="removeRolesById(scope.row,item1.id)"
                >{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级权限 -->
              <el-col :span="19">
                <!-- 二级权限中在套一个row和col其中row中包含二级和三级权限 -->
                <el-row
                  :class="[i2 === 0 ? '' : 'tborder','.vcenter']"
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                >
                  <el-col :span="6">
                    <el-tag
                      size="medium"
                      type="success"
                      closable
                      @close="removeRolesById(scope.row,item2.id)"
                    >{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      size="medium"
                      type="warning"
                      v-for="(item3) in item2.children"
                      :key="item3.id"
                      closable
                      @close="removeRolesById(scope.row,item3.id)"
                    >{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <!-- <pre>
             {{ scope.row}}
            </pre> -->
          </template>
        </el-table-column>
        <el-table-column align="center" prop="roleName" label="角色名称"></el-table-column>
        <el-table-column align="center" prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column align="center" label="操作">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click="editRolesList(scope.row.id)"
            >编辑</el-button>
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="removeRoles(scope.row.id)"
            >删除</el-button>
            <el-button
              size="mini"
              type="warning"
              icon="el-icon-setting"
              @click="showAllotRightsList(scope.row)"
            >分配角色</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加角色 -->
    <el-dialog title="添加角色" :visible.sync="addRolesDialog" width="50%" @close="addRolesClear">
      <el-form ref="addRolesRef" :model="addRolesList" :rules="addRolesRules" label-width="80px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRolesList.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addRolesList.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRolesDialog = false">取 消</el-button>
        <el-button type="primary" @click="addRoles">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑角色 -->
    <el-dialog title="编辑角色" :visible.sync="editDialog" width="50%" @close="editRolesClear">
      <el-form ref="editRolesRef" :model="editRoles" :rules="editRolesRules" label-width="80px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editRoles.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editRoles.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialog = false">取 消</el-button>
        <el-button type="primary" @click="renewRoles">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配角色权限 -->
    <el-dialog title="分配角色" :visible.sync="alloRightsDialog" width="50%" @close="allotRightsClear">
      <!-- 树形控件 -->
      <el-tree
        :data="allotRightList"
        :props="treeProps"
        ref="treeRef"
        :default-expand-all="true"
        show-checkbox
        node-key="id"
        :default-checked-keys="leafKeys"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="alloRightsDialog = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      // 角色列表
      rolesList: [],

      // 添加角色列表
      addRolesList: {
        roleName: '',
        roleDesc: ''
      },

      // 添加输入框验证
      addRolesRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10个字符', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5个字符', trigger: 'blur' }
        ]
      },

      addRolesDialog: false,
      // 编辑数据
      editRoles: {},
      editRolesRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10个字符', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5个字符', trigger: 'blur' }
        ]
      },
      editDialog: false,

      // 分配角色对话框的显隐
      alloRightsDialog: false,

      // 分配角色权限的接收数组
      allotRightList: [],

      // 定义树形控件配置属性
      treeProps: {
        label: 'authName',
        children: 'children'
      },

      // 默认选中的数组id
      leafKeys: [],

      // 当前即将分配的角色id
      roleId: ''
    }
  },
  created () {
    this.getRoleList()
  },
  methods: {
    // 渲染表格
    async getRoleList () {
      const { data: res } = await this.$http.get('/roles')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.rolesList = res.data
    },

    // 关闭弹框 清空表单
    addRolesClear () {
      this.$refs.addRolesRef.resetFields()
    },

    // 添加数据
    addRoles () {
      this.$refs.addRolesRef.validate(async valid => {
        // console.log(valid)
        if (!valid) return
        const { data: res } = await this.$http.post('/roles', this.addRolesList)
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.getRoleList()
        this.addRolesDialog = false
      })
    },

    // 关闭清空表单
    editRolesClear () {
      this.$refs.editRolesRef.resetFields()
    },

    // 编辑数据先根据id获取数据
    async editRolesList (id) {
      // console.log(id)
      const { data: res } = await this.$http.get('/roles/' + id)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.editRoles = res.data
      this.getRoleList()
      this.editDialog = true
    },

    // 更改数据
    async renewRoles () {
      const { data: res } = await this.$http.put(`/roles/${this.editRoles.roleId}`, {
        roleName: this.editRoles.roleName,
        roleDesc: this.editRoles.roleDesc
      })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      this.getRoleList()
      this.editDialog = false
    },

    // 删除用户
    async removeRoles (id) {
      const deleteConfirm = await this.$confirm('此操作将永久删除该用户角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (deleteConfirm !== 'confirm') return this.$message.info('您已取消删除操作')
      const { data: res } = await this.$http.delete(`/roles/${id}`)
      this.$message.success(res.meta.msg)
      this.getRoleList()
    },

    // 根据id删除角色的权限
    async removeRolesById (role, rightId) {
      // console.log(role, rightId)
      // 先给一个提示是否确认删除
      const RoleConfirm = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (RoleConfirm !== 'confirm') return this.$message.info('您取消了删除')
      // console.log('确认删除')
      const { data: res } = await this.$http.delete(`/roles/${role.id}/rights/${rightId}`)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      // 成功之后刷新列表
      role.children = res.data
    },

    // 获取所有的权限数据
    async showAllotRightsList (role) {
      this.roleId = role.id
      const { data: res } = await this.$http.get('/rights/tree')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.allotRightList = res.data
      this.alloRightsDialog = true
      // 获取第三方的节点
      this.getLeafKeys(role, this.leafKeys)
    },

    // 利用递归的方法获取角色下第三级的所有权限
    getLeafKeys (node, arr) {
      // console.log(node, arr)
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => this.getLeafKeys(item, arr))
    },

    // 点击关闭清空权限
    allotRightsClear () {
      this.leafKeys = []
    },

    // 点击分配权限
    async allotRights () {
      // 先根据提供的方法来获取所有节点的id
      const nodeKeys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      // console.log(nodeKeys)
      // 在将获取的数据转换为字符串
      const keyStr = nodeKeys.join(',')
      const { data: res } = await this.$http.post(`/roles/${this.roleId}/rights`, {
        rids: keyStr
      })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      this.getRoleList()
      this.alloRightsDialog = false
    }
  }
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 8px;
}
// 上边框
.tborder {
  border-top: 1px solid #eee;
}

// 下边框
.btmborder {
  border-bottom: 1px solid #eee;
}

// 居中
.vcenter {
  display: flex;
  align-items: center;
}
</style>
